package com.homestay.dao.impl;

import com.homestay.beans.Admins;
import com.homestay.dao.AdminsDao;
import com.homestay.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import java.sql.SQLException;

// 数据访问层实现类
public class AdminsDaoImpl implements AdminsDao {

    QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

    @Override
    public Admins login(String username, String password) {
        String sql = "select * from tb_admins where username = ? and password = ?";
        try {
            return queryRunner.query(sql, new BeanHandler<>(Admins.class), username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Admins queryByUsername(String username) {
        String sql = "select * from tb_admins where username = ?";
        try {
            return queryRunner.query(sql, new BeanHandler<>(Admins.class), username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int add(Admins admin) {
        String sql = "insert into tb_admins values(null,?,?,now(),now())";
        try {
            return queryRunner.update(sql, admin.getUsername(), admin.getPassword());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
